# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-06 7:19
# File     : simple_logging.py
# Project  : codebuddy_craft
# Desc     :

# backend/middleware/simple_logging.py
"""
简单日志中间件 📝

使用FastAPI内置功能的简单日志中间件
"""

import time
from fastapi import Request, Response
from backend.utils.logger import get_logger
from backend.utils.log_utils import log_api_request, log_api_response

logger = get_logger("http_middleware")


async def log_requests_middleware(request: Request, call_next):
    """简单的请求日志中间件函数"""
    start_time = time.time()

    # 记录请求信息
    request_info = {
        "method": request.method,
        "path": request.url.path,
        "query_params": dict(request.query_params),
        "client_host": request.client.host if request.client else "unknown",
        "user_agent": request.headers.get("user-agent", "unknown"),
        "content_type": request.headers.get("content-type"),
        "content_length": request.headers.get("content-length")
    }

    log_api_request(request_info)

    try:
        # 处理请求
        response = await call_next(request)

        # 计算处理时间
        process_time = time.time() - start_time

        # 记录响应信息
        response_info = {
            "method": request.method,
            "path": request.url.path,
            "status_code": response.status_code,
            "duration": process_time,
            "response_size": response.headers.get("content-length")
        }

        log_api_response(response_info)

        # 添加响应头
        response.headers["X-Process-Time"] = str(process_time)

        return response

    except Exception as e:
        process_time = time.time() - start_time

        logger.error(
            f"❌ 请求处理失败: {request.method} {request.url.path} ({process_time:.3f}s)",
            exc_info=True,
            extra={
                "event_type": "request_error",
                "method": request.method,
                "path": request.url.path,
                "duration": process_time,
                "client_host": request.client.host if request.client else "unknown"
            }
        )
        raise
